package com.wt.chat.service.impl;

import com.wt.chat.cache.RedisCache;
import com.wt.chat.entity.Message;
import com.wt.chat.mapper.MessageMapper;
import com.wt.chat.service.MessageService;
import com.wt.chat.utils.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 * @author: wangtao
 * @date:9:39 2019/11/12
 * @email:taow02@jumei.com
 */
@Service
public class MessageServiceImpl implements MessageService {

	@Autowired
	private MessageMapper messageMapper;

	@Autowired
	private RedisCache redisCache;

	@Override
	public Map<String, List<Message>> pollingByKefuId(Integer kefuId) {
		String key = Keys.getNewMessageDialogsKey(Keys.TAG.KEFU, kefuId + "");
		List<String> list = redisCache.range(key, 0, -1, String.class);
		if(list == null || list.isEmpty()){
			return new HashMap<>();
		}
		redisCache.ltrim(key, list.size(), -1);
		Map<String, List<Message>> dialogMsgMap = new HashMap<>();
		list.forEach(dialogId -> dialogMsgMap
				.put(dialogId, redisCache.range(Keys.getDialogMessageRedisKey(dialogId), 0, -1, Message.class)));
		return dialogMsgMap;
	}

	@Override
	public Map<String, List<Message>> pollingByUserId(Integer userId) {
		String key = Keys.getNewMessageDialogsKey(Keys.TAG.USER, userId + "");
		List<String> list = redisCache.range(key, 0, -1, String.class);
		if(list == null || list.isEmpty()){
			return new HashMap<>();
		}
		redisCache.ltrim(key, list.size(), -1);
		Map<String, List<Message>> dialogMsgMap = new HashMap<>();
		list.forEach(dialogId -> dialogMsgMap
				.put(dialogId, redisCache.range(Keys.getDialogMessageRedisKey(dialogId), 0, -1, Message.class)));
		return dialogMsgMap;
	}

	@Override
	public List<Message> findByDialogId(Integer dialogId) {
		//先从缓存中取，如果是当前会话，缓存中有，直接从缓存拿
		List<Message> messages = redisCache.range(Keys.getDialogMessageRedisKey(dialogId + ""), 0, -1, Message.class);
		if(messages == null || messages.isEmpty()) {
			return messages;
		}
		return messageMapper.findByDialog(dialogId);
	}

	@Override
	public void sendMessage(Message message) {
		redisCache.rightPush(Keys.getDialogMessageRedisKey(message.getDialogId() + ""), message);
		//存入数据库的一律视为已读，未读标记在redis中有
		message.setStatus(Message.MsgStatus.READ.getValue());
		messageMapper.insertSelective(message);
	}

	@Override
	public void notify(Integer notifyId, Message message) {
		boolean isKefuSend = message.getSender() == Message.SenderType.KEFU.getValue();
		redisCache.rightPush(Keys.getNewMessageDialogsKey(isKefuSend ? Keys.TAG.USER : Keys.TAG.KEFU, notifyId + ""),
				message.getDialogId());
	}

}
